<template>
  <div class="user-list-container">
    <div class="header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="handleAdd">新增用户</el-button>
    </div>

    <div class="search-form">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="用户名">
          <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="queryParams.nickname" placeholder="请输入昵称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="UserStatus.ENABLED" />
            <el-option label="禁用" :value="UserStatus.DISABLED" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="queryParams.role" placeholder="请选择角色" clearable>
            <el-option v-for="role in roleOptions" :key="role.value" :label="role.label" :value="role.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table v-loading="loading" :data="userList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="用户信息" width="250">
        <template #default="{ row }">
          <div class="user-info">
            <el-avatar :src="row.avatar" :size="40" />
            <div class="user-detail">
              <div class="username">{{ row.username }}</div>
              <div class="nickname">{{ row.nickname }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column label="角色" width="200">
        <template #default="{ row }">
          <el-tag v-for="role in row.roles" :key="role" size="small" class="role-tag">
            {{ getRoleName(role) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === UserStatus.ENABLED ? 'success' : 'danger'">
            {{ row.status === UserStatus.ENABLED ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="warning" size="small" @click="handleResetPassword(row)">重置密码</el-button>
          <el-button
            :type="row.status === UserStatus.ENABLED ? 'danger' : 'success'"
            size="small"
            @click="handleStatusChange(row)"
          >
            {{ row.status === UserStatus.ENABLED ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 用户表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="userForm.id !== undefined" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="userForm.id === undefined">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="uploadAvatarRequest"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="userForm.roles" multiple placeholder="请选择角色">
            <el-option v-for="role in roleOptions" :key="role.value" :label="role.label" :value="role.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="UserStatus.ENABLED">启用</el-radio>
            <el-radio :label="UserStatus.DISABLED">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog v-model="resetPasswordDialogVisible" title="重置密码" width="500px">
      <el-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="resetPasswordRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPasswordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitResetPasswordForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { getUserPage, createUser, updateUser, deleteUser, updateUserStatus, resetPassword, uploadAvatar } from '@/api/system/user.ts';
import { getAllRoles } from '@/api/system/role';
import { UserStatus, UserRole, type User, type UserQueryParams, type UserRequest, type ResetPasswordRequest, type Role } from '@/types/system/user.ts';
import type { FormInstance, UploadRequestOptions } from 'element-plus';

// 查询参数
const queryParams = reactive<UserQueryParams>({
  pageNum: 1,
  pageSize: 10,
  username: '',
  nickname: '',
  status: undefined,
  role: undefined
});

// 用户列表数据
const userList = ref<User[]>([]);
const total = ref(0);
const loading = ref(false);

// 角色选项
const roles = ref<Role[]>([]);
const roleOptions = computed(() => {
  return Object.values(UserRole).map(role => ({
    value: role,
    label: getRoleName(role)
  }));
});

// 获取角色名称
const getRoleName = (roleCode: string) => {
  switch (roleCode) {
    case UserRole.ADMIN:
      return '管理员';
    case UserRole.DEVELOPER:
      return '开发者';
    case UserRole.USER:
      return '普通用户';
    default:
      return roleCode;
  }
};

// 用户表单对话框
const dialogVisible = ref(false);
const dialogTitle = ref('');
const userFormRef = ref<FormInstance>();
const userForm = reactive<UserRequest>({
  username: '',
  nickname: '',
  password: '',
  email: '',
  phone: '',
  avatar: '',
  status: UserStatus.ENABLED,
  roles: []
});

// 表单校验规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  roles: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
};

// 重置密码对话框
const resetPasswordDialogVisible = ref(false);
const resetPasswordFormRef = ref<FormInstance>();
const resetPasswordForm = reactive<ResetPasswordRequest>({
  userId: 0,
  newPassword: ''
});

// 重置密码校验规则
const resetPasswordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
};

// 获取用户列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getUserPage(queryParams);
    userList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.error('获取用户列表失败', error);
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 获取所有角色
const getRoles = async () => {
  try {
    const res = await getAllRoles();
    roles.value = res.data;
  } catch (error) {
    console.error('获取角色列表失败', error);
    ElMessage.error('获取角色列表失败');
  }
};

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  queryParams.username = '';
  queryParams.nickname = '';
  queryParams.status = undefined;
  queryParams.role = undefined;
  handleQuery();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  getList();
};

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  queryParams.pageNum = 1;
  getList();
};

// 新增用户
const handleAdd = () => {
  dialogTitle.value = '新增用户';
  userForm.id = undefined;
  userForm.username = '';
  userForm.nickname = '';
  userForm.password = '';
  userForm.email = '';
  userForm.phone = '';
  userForm.avatar = '';
  userForm.status = UserStatus.ENABLED;
  userForm.roles = [];
  dialogVisible.value = true;
};

// 编辑用户
const handleEdit = (row: User) => {
  dialogTitle.value = '编辑用户';
  userForm.id = row.id;
  userForm.username = row.username;
  userForm.nickname = row.nickname;
  userForm.password = undefined;
  userForm.email = row.email;
  userForm.phone = row.phone;
  userForm.avatar = row.avatar;
  userForm.status = row.status;
  userForm.roles = row.roles;
  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return;

  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (userForm.id) {
          await updateUser(userForm);
          ElMessage.success('更新用户成功');
        } else {
          await createUser(userForm);
          ElMessage.success('创建用户成功');
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error('提交用户表单失败', error);
        ElMessage.error('提交用户表单失败');
      }
    }
  });
};

// 删除用户
const handleDelete = async (row: User) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 ${row.username} 吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await deleteUser(row.id);
    ElMessage.success('删除用户成功');
    getList();
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除用户失败', error);
      ElMessage.error('删除用户失败');
    }
  }
};

// 修改用户状态
const handleStatusChange = async (row: User) => {
  const newStatus = row.status === UserStatus.ENABLED ? UserStatus.DISABLED : UserStatus.ENABLED;
  const statusText = newStatus === UserStatus.ENABLED ? '启用' : '禁用';

  try {
    await ElMessageBox.confirm(`确定要${statusText}用户 ${row.username} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await updateUserStatus(row.id, newStatus);
    ElMessage.success(`${statusText}用户成功`);
    getList();
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error(`${statusText}用户失败`, error);
      ElMessage.error(`${statusText}用户失败`);
    }
  }
};

// 重置密码
const handleResetPassword = (row: User) => {
  resetPasswordForm.userId = row.id;
  resetPasswordForm.newPassword = '';
  resetPasswordDialogVisible.value = true;
};

// 提交重置密码表单
const submitResetPasswordForm = async () => {
  if (!resetPasswordFormRef.value) return;

  await resetPasswordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await resetPassword(resetPasswordForm);
        ElMessage.success('重置密码成功');
        resetPasswordDialogVisible.value = false;
      } catch (error) {
        console.error('重置密码失败', error);
        ElMessage.error('重置密码失败');
      }
    }
  });
};

// 上传头像前的校验
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

// 自定义上传请求
const uploadAvatarRequest = async (options: UploadRequestOptions) => {
  try {
    const res = await uploadAvatar(options.file as File);
    userForm.avatar = res.data;
    ElMessage.success('上传头像成功');
  } catch (error) {
    console.error('上传头像失败', error);
    ElMessage.error('上传头像失败');
  }
};

onMounted(() => {
  getList();
  getRoles();
});
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-detail {
  margin-left: 10px;
}

.username {
  font-weight: bold;
  margin-bottom: 5px;
}

.nickname {
  font-size: 12px;
  color: #666;
}

.role-tag {
  margin-right: 5px;
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
